import PureRunnableGroupDetail from '../components/runnable-group-detail';
import * as RunnableGroupAction from 'actions/runnable-group';
import { getFetchStatus } from 'actions/util';
import { getMessage } from 'messages';
import _ from 'lodash';
import * as React from 'react';
import * as ReactRedux from 'react-redux';

const mapStateToProps = (state) => {
  return {
    isFetching: getFetchStatus(state, RunnableGroupAction.get),
    detail: state.runnableGroup
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  const initFetch = () => {
    return dispatch(RunnableGroupAction.get(ownProps.id))
      .then(({ error, payload }) => {
        // have runtimes, fetch the first runtime's units
        if (!!error) {
          return Promise.reject(payload.message);
        }
        if (!_.isEmpty(payload.runnableRuntimes)) {
          dispatch(RunnableGroupAction.listUnitsByRuntimeId(payload.runnableRuntimes[0].id));
        }
      });
  };

  return {
    onRuntimeTabClick: (runtimeId) => {
      dispatch(RunnableGroupAction.listUnitsByRuntimeId(runtimeId));
    },
    initFetch,
    onRuntimeCreate: (params) => {
      return dispatch(RunnableGroupAction.createRuntime(params));
    },
    onRuntimeDelete: (runtimeId) => {
      return dispatch(RunnableGroupAction.deleteRuntime(runtimeId))
        .then(initFetch());
    },
    onRuntimeRename: (runtimeId, name) => {
      return dispatch(RunnableGroupAction.renameRuntime(runtimeId, name));
    }
  };
};

class RunnableGroupDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this.props.initFetch()
      .catch(errorMessage => {
        this.setState({ error: getMessage(errorMessage) });
      });
  }

  render() {
    return <PureRunnableGroupDetail error={this.state.error} {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(RunnableGroupDetail);
